home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1995 August: Tool Chest / Dev.CD Aug 95 TC / Dev.CD Aug 95 TC.toast / Sample Code / Snippets / Toolbox / Password / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-10  |  25.7 KB  |  756 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    This is just a hacked version of CSample.  Ignore any bits referring to the
  4. #    traffic lights, etc.
  5. #
  6. ------------------------------------------------------------------------------*/
  7.  
  8.  
  9. #include <Values.h>
  10. #include <Types.h>
  11. #include <Resources.h>
  12. #include <QuickDraw.h>
  13. #include <Fonts.h>
  14. #include <Events.h>
  15. #include <Windows.h>
  16. #include <Menus.h>
  17. #include <TextEdit.h>
  18. #include <Dialogs.h>
  19. #include <Desk.h>
  20. #include <ToolUtils.h>
  21. #include <Memory.h>
  22. #include <SegLoad.h>
  23. #include <Files.h>
  24. #include <OSUtils.h>
  25. #include <OSEvents.h>
  26. #include <DiskInit.h>
  27. #include <Packages.h>
  28. #include <Traps.h>
  29. #include <Limits.h>
  30. #include "Sample.h"        /* bring in all the #defines for Sample */
  31.  
  32. #include "Password.h"
  33.  
  34. /* The "g" prefix is used to emphasize that a variable is global. */
  35.  
  36. /* GMac is used to hold the result of a SysEnvirons call. This makes
  37.    it convenient for any routine to check the environment. */
  38. SysEnvRec    gMac;                /* set up by Initialize */
  39.  
  40. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  41.    trap is available. If it is false, we know that we must call GetNextEvent. */
  42. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  43.  
  44. /* GInBackground is maintained by our osEvent handling routines. Any part of
  45.    the program can check it to find out if it is currently in the background. */
  46. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  47.  
  48.  
  49. /* The following globals are the state of the window. If we supported more than
  50.    one window, they would be attatched to each document, rather than globals. */
  51.  
  52. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  53.    actual prototypes for parameter type checking. */
  54. void EventLoop( void );
  55. void DoEvent( EventRecord *event );
  56. void AdjustCursor( Point mouse, RgnHandle region );
  57. void GetGlobalMouse( Point *mouse );
  58. void DoUpdate( WindowPtr window );
  59. void DoActivate( WindowPtr window, Boolean becomingActive );
  60. void DoContentClick( WindowPtr window );
  61. void DrawWindow( WindowPtr window );
  62. void AdjustMenus( void );
  63. void DoMenuCommand( long menuResult );
  64. void SetLight( WindowPtr window, Boolean newStopped );
  65. Boolean DoCloseWindow( WindowPtr window );
  66. void Terminate( void );
  67. void Initialize( void );
  68. Boolean GoGetRect( short rectID, Rect *theRect );
  69. void ForceEnvirons( void );
  70. Boolean IsAppWindow( WindowPtr window );
  71. Boolean IsDAWindow( WindowPtr window );
  72. Boolean TrapAvailable(short theTrap);
  73. void AlertUser( void );
  74.  
  75.  
  76. /* Define HiWrd and LoWrd macros for efficiency. */
  77. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  78. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  79.  
  80. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  81.    dependency on the ordering of fields within a Rect */
  82. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  83. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  84.  
  85.  
  86. extern void _DataInit();
  87.  
  88. /* This routine is part of the MPW runtime library. This external
  89.    reference to it is done so that we can unload its segment, %A5Init. */
  90.  
  91.  
  92. #pragma segment Main
  93. main()
  94. {
  95.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  96.     
  97.     /* 1.01 - call to ForceEnvirons removed */
  98.     
  99.     /*    If you have stack requirements that differ from the default,
  100.         then you could use SetApplLimit to increase StackSpace at 
  101.         this point, before calling MaxApplZone. */
  102.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  103.  
  104.     Initialize();                    /* initialize the program */
  105.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  106.  
  107.     EventLoop();                    /* call the main event loop */
  108. }
  109.  
  110.  
  111. /*    Get events forever, and handle them by calling DoEvent.
  112.     Get the events by calling WaitNextEvent, if it's available, otherwise
  113.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  114.  
  115. #pragma segment Main
  116. void EventLoop()
  117. {
  118.     RgnHandle    cursorRgn;
  119.     Boolean        gotEvent;
  120.     EventRecord    event;
  121.     Point        mouse;
  122.  
  123.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  124.     do {
  125.         /* use WNE if it is available */
  126.         if ( gHasWaitNextEvent ) {
  127.             GetGlobalMouse(&mouse);
  128.             AdjustCursor(mouse, cursorRgn);
  129.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  130.         }
  131.         else {
  132.             SystemTask();
  133.             gotEvent = GetNextEvent(everyEvent, &event);
  134.         }
  135.         if ( gotEvent ) {
  136.             /* make sure we have the right cursor before handling the event */
  137.             AdjustCursor(event.where, cursorRgn);
  138.             DoEvent(&event);
  139.         }
  140.         /*    If you are using modeless dialogs that have editText items,
  141.             you will want to call IsDialogEvent to give the caret a chance
  142.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  143.             for a non-NIL value before calling IsDialogEvent. */
  144.     } while ( true );    /* loop forever; we quit via ExitToShell */
  145. } /*EventLoop*/
  146.  
  147.  
  148. /* Do the right thing for an event. Determine what kind of event it is, and call
  149.  the appropriate routines. */
  150.  
  151. #pragma segment Main
  152. void DoEvent(event)
  153.     EventRecord    *event;
  154. {
  155.     short        part, err;
  156.     WindowPtr    window;
  157.     Boolean        hit;
  158.     char        key;
  159.     Point        aPoint;
  160.  
  161.     switch ( event->what ) {
  162.         case mouseDown:
  163.             part = FindWindow(event->where, &window);
  164.             switch ( part ) {
  165.                 case inMenuBar:                /* process a mouse menu command (if any) */
  166.                     AdjustMenus();
  167.                     DoMenuCommand(MenuSelect(event->where));
  168.                     break;
  169.                 case inSysWindow:            /* let the system handle the mouseDown */
  170.                     SystemClick(event, window);
  171.                     break;
  172.                 case inContent:
  173.                     if ( window != FrontWindow() ) {
  174.                         SelectWindow(window);
  175.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  176.                     } else
  177.                         DoContentClick(window);
  178.                     break;
  179.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  180.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  181.                     break;
  182.                 case inGrow:
  183.                     break;
  184.                 case inZoomIn:
  185.                 case inZoomOut:
  186.                     hit = TrackBox(window, event->where, part);
  187.                     if ( hit ) {
  188.                         SetPort(window);                /* the window must be the current port... */
  189.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  190.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  191.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  192.                     }
  193.                     break;
  194.             }
  195.             break;
  196.         case keyDown:
  197.         case autoKey:                        /* check for menukey equivalents */
  198.             key = event->message & charCodeMask;
  199.             if ( event->modifiers & cmdKey )            /* Command key down */
  200.                 if ( event->what == keyDown ) {
  201.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  202.                     DoMenuCommand(MenuKey(key));
  203.                 }
  204.             break;
  205.         case activateEvt:
  206.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  207.             break;
  208.         case updateEvt:
  209.             DoUpdate((WindowPtr) event->message);
  210.             break;
  211.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  212.             to a diskEvt, so that the user can format a floppy. */
  213.         case diskEvt:
  214.             if ( HiWord(event->message) != noErr ) {
  215.                 SetPt(&aPoint, kDILeft, kDITop);
  216.                 err = DIBadMount(aPoint, event->message);
  217.             }
  218.             break;
  219.         case kOSEvent:
  220.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  221.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  222.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  223.                     gInBackground = (event->message & kResumeMask) == 0;
  224.                     DoActivate(FrontWindow(), !gInBackground);
  225.                     break;
  226.             }
  227.             break;
  228.     }
  229. } /*DoEvent*/
  230.  
  231.  
  232. /*    Change the cursor's shape, depending on its position. This also calculates the region
  233.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  234.     that region, an event would be generated, causing this routine to be called,
  235.     allowing us to change the region to the region the mouse is currently in. If
  236.     there is more to the event than just “the mouse moved”, we get called before the
  237.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  238.     this is called again before we     fall back into WNE. */
  239.  
  240. #pragma segment Main
  241. void AdjustCursor(mouse,region)
  242.     Point        mouse;
  243.     RgnHandle    region;
  244. {
  245.     WindowPtr    window;
  246.     RgnHandle    arrowRgn;
  247.     RgnHandle    plusRgn;
  248.     Rect        globalPortRect;
  249.  
  250.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  251.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  252.         /* calculate regions for different cursor shapes */
  253.         arrowRgn = NewRgn();
  254.         plusRgn = NewRgn();
  255.  
  256.         /* start with a big, big rectangular region */
  257.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  258.  
  259.         /* calculate plusRgn */
  260.         if ( IsAppWindow(window) ) {
  261.             SetPort(window);    /* make a global version of the viewRect */
  262.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  263.             globalPortRect = window->portRect;
  264.             RectRgn(plusRgn, &globalPortRect);
  265.             SectRgn(plusRgn, window->visRgn, plusRgn);
  266.             SetOrigin(0, 0);
  267.         }
  268.  
  269.         /* subtract other regions from arrowRgn */
  270.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  271.  
  272.         /* change the cursor and the region parameter */
  273.         if ( PtInRgn(mouse, plusRgn) ) {
  274.             SetCursor(*GetCursor(plusCursor));
  275.             CopyRgn(plusRgn, region);
  276.         } else {
  277.             SetCursor(&qd.arrow);
  278.             CopyRgn(arrowRgn, region);
  279.         }
  280.  
  281.         /* get rid of our local regions */
  282.         DisposeRgn(arrowRgn);
  283.         DisposeRgn(plusRgn);
  284.     }
  285. } /*AdjustCursor*/
  286.  
  287.  
  288. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  289.     it will return either a pending event or a null event. In either case,
  290.     the where field of the event record will contain the current position
  291.     of the mouse in global coordinates and the modifiers field will reflect
  292.     the current state of the modifiers. Another way to get the global
  293.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  294.     being sure that thePort is set to a valid port. */
  295.  
  296. #pragma segment Main
  297. void GetGlobalMouse(mouse)
  298.     Point    *mouse;
  299. {
  300.     EventRecord    event;
  301.     
  302.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  303.     *mouse = event.where;                /* just the mouse position */
  304. } /*GetGlobalMouse*/
  305.  
  306.  
  307. /*    This is called when an update event is received for a window.
  308.     It calls DrawWindow to draw the contents of an application window.
  309.     As an efficiency measure that does not have to be followed, it
  310.     calls the drawing routine only if the visRgn is non-empty. This
  311.     will handle situations where calculations for drawing or drawing
  312.     itself is very time-consuming. */
  313.  
  314. #pragma segment Main
  315. void DoUpdate(window)
  316.     WindowPtr    window;
  317. {
  318.     if ( IsAppWindow(window) ) {
  319.         BeginUpdate(window);                /* this sets up the visRgn */
  320.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  321.             DrawWindow(window);
  322.         EndUpdate(window);
  323.     }
  324. } /*DoUpdate*/
  325.  
  326.  
  327. /*    This is called when a window is activated or deactivated.
  328.     In Sample, the Window Manager's handling of activate and
  329.     deactivate events is sufficient. Other applications may have
  330.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  331.  
  332. #pragma segment Main
  333. void DoActivate(window, becomingActive)
  334.     WindowPtr    window;
  335.     Boolean        becomingActive;
  336. {
  337.     if ( IsAppWindow(window) ) {
  338.         if ( becomingActive )
  339.             /* do whatever you need to at activation */ ;
  340.         else
  341.             /* do whatever you need to at deactivation */ ;
  342.     }
  343. } /*DoActivate*/
  344.  
  345.  
  346. /*    This is called when a mouse-down event occurs in the content of a window.
  347.     Other applications might want to call FindControl, TEClick, etc., to
  348.     further process the click. */
  349.  
  350. #pragma segment Main
  351. void DoContentClick(window)
  352.     WindowPtr    window;
  353. {
  354. #pragma unused (window)
  355. } /*DoContentClick*/
  356.  
  357.  
  358. /* Draw the contents of the application window. We do some drawing in color, using
  359.    Classic QuickDraw's color capabilities. This will be black and white on old
  360.    machines, but color on color machines. At this point, the window’s visRgn
  361.    is set to allow drawing only where it needs to be done. */
  362.  
  363. #pragma segment Main
  364. void DrawWindow(window)
  365.     WindowPtr    window;
  366. {
  367.     SetPort(window);
  368.  
  369.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  370. } /*DrawWindow*/
  371.  
  372.  
  373. /*    Enable and disable menus based on the current state.
  374.     The user can only select enabled menu items. We set up all the menu items
  375.     before calling MenuSelect or MenuKey, since these are the only times that
  376.     a menu item can be selected. Note that MenuSelect is also the only time
  377.     the user will see menu items. This approach to deciding what enable/
  378.     disable state a menu item has the advantage of concentrating all
  379.     the decision-making in one routine, as opposed to being spread throughout
  380.     the application. Other application designs may take a different approach
  381.     that is just as valid. */
  382.  
  383. #pragma segment Main
  384. void AdjustMenus()
  385. {
  386.     WindowPtr    window;
  387.     MenuHandle    menu;
  388.  
  389.     window = FrontWindow();
  390.  
  391.     menu = GetMenuHandle(mFile);
  392.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  393.         EnableItem(menu, iClose);
  394.     else
  395.         DisableItem(menu, iClose);    /* but not our traffic light window */
  396.  
  397.     menu = GetMenuHandle(mEdit);
  398.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  399.         EnableItem(menu, iUndo);
  400.         EnableItem(menu, iCut);
  401.         EnableItem(menu, iCopy);
  402.         EnableItem(menu, iClear);
  403.         EnableItem(menu, iPaste);
  404.     } else {                        /* …but we don’t use it */
  405.         DisableItem(menu, iUndo);
  406.         DisableItem(menu, iCut);
  407.         DisableItem(menu, iCopy);
  408.         DisableItem(menu, iClear);
  409.         DisableItem(menu, iPaste);
  410.     }
  411.     
  412.     menu = GetMenuHandle(mPassword);
  413.         EnableItem(menu, iTwoItem);
  414.         EnableItem(menu, iDifferentFont);
  415.         EnableItem(menu, iInternalBuffer);
  416.     
  417. } /*AdjustMenus*/
  418.  
  419.  
  420. /*    This is called when an item is chosen from the menu bar (after calling
  421.     MenuSelect or MenuKey). It performs the right operation for each command.
  422.     It is good to have both the result of MenuSelect and MenuKey go to
  423.     one routine like this to keep everything organized. */
  424.  
  425. #pragma segment Main
  426. void DoMenuCommand(menuResult)
  427.     long        menuResult;
  428. {
  429.     short        menuID;                /* the resource ID of the selected menu */
  430.     short        menuItem;            /* the item number of the selected menu */
  431.     short        itemHit;
  432.     Str255        daName;
  433.     short        daRefNum;
  434.     Boolean        handledByDA;
  435.  
  436.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  437.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  438.     switch ( menuID ) {
  439.         case mApple:
  440.             switch ( menuItem ) {
  441.                 case iAbout:        /* bring up alert for About */
  442.                     itemHit = Alert(rAboutAlert, nil);
  443.                     break;
  444.                 default:            /* all non-About items in this menu are DAs */
  445.                     /* type Str255 is an array in MPW 3 */
  446.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  447.                     daRefNum = OpenDeskAcc(daName);
  448.                     break;
  449.             }
  450.             break;
  451.         case mFile:
  452.             switch ( menuItem ) {
  453.                 case iClose:
  454.                     DoCloseWindow(FrontWindow());
  455.                     break;
  456.                 case iQuit:
  457.                     Terminate();
  458.                     break;
  459.             }
  460.             break;
  461.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  462.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  463.             break;
  464.         case mPassword:
  465.             switch ( menuItem ) {
  466.                 case iTwoItem:
  467.                     DisplayPassword(TwoItemDialog());
  468.                     break;
  469.                 case iDifferentFont:
  470.                     DisplayPassword(DifferentFontDialog());
  471.                     break;
  472.                 case iInternalBuffer:
  473.                     DisplayPassword(InternalBufferDialog());
  474.                     break;
  475.             }
  476.             break;
  477.     }
  478.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  479. } /*DoMenuCommand*/
  480.  
  481.  
  482. /* Close a window. This handles desk accessory and application windows. */
  483.  
  484. /*    1.01 - At this point, if there was a document associated with a
  485.     window, you could do any document saving processing if it is 'dirty'.
  486.     DoCloseWindow would return true if the window actually closed, i.e.,
  487.     the user didn’t cancel from a save dialog. This result is handy when
  488.     the user quits an application, but then cancels the save of a document
  489.     associated with a window. */
  490.  
  491. #pragma segment Main
  492. Boolean DoCloseWindow(window)
  493.     WindowPtr    window;
  494. {
  495.     if ( IsDAWindow(window) )
  496.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  497.     else if ( IsAppWindow(window) )
  498.         CloseWindow(window);
  499.     return true;
  500. } /*DoCloseWindow*/
  501.  
  502.  
  503. /**************************************************************************************
  504. *** 1.01 DoCloseBehind(window) was removed ***
  505.  
  506.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  507.     and not having to worry about updating the windows, but it suffered
  508.     from a fatal flaw. If a desk accessory owned two windows, it would
  509.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  510.     got around to calling DoCloseWindow for that other window that was already
  511.     closed, things would go very poorly. Another option would be to have a
  512.     procedure, GetRearWindow, that would go through the window list and return
  513.     the last window. Instead, we decided to present the standard approach
  514.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  515.     has a potential benefit in that the window whose document needs to be saved
  516.     may be visible since it is the front window, therefore decreasing the
  517.     chance of user confusion. For aesthetic reasons, the windows in the
  518.     application should be checked for updates periodically and have the
  519.     updates serviced.
  520. **************************************************************************************/
  521.  
  522.  
  523. /* Clean up the application and exit. We close all of the windows so that
  524.  they can update their documents, if any. */
  525.  
  526. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  527.     shell, but will return instead. */
  528.  
  529. #pragma segment Main
  530. void Terminate()
  531. {
  532.     WindowPtr    aWindow;
  533.     Boolean        closed;
  534.     
  535.     closed = true;
  536.     do {
  537.         aWindow = FrontWindow();                /* get the current front window */
  538.         if (aWindow != nil)
  539.             closed = DoCloseWindow(aWindow);    /* close this window */    
  540.     }
  541.     while (closed && (aWindow != nil));
  542.     if (closed)
  543.         ExitToShell();                            /* exit if no cancellation */
  544. } /*Terminate*/
  545.  
  546.  
  547. #ifdef powerc
  548.    QDGlobals    qd;
  549. #endif
  550.  
  551.  
  552. /*    Set up the whole world, including global variables, Toolbox managers,
  553.     and menus. We also create our one application window at this time.
  554.     Since window storage is non-relocateable, how and when to allocate space
  555.     for windows is very important so that heap fragmentation does not occur.
  556.     Because Sample has only one window and it is only disposed when the application
  557.     quits, we will allocate its space here, before anything that might be a locked
  558.     relocatable object gets into the heap. This way, we can force the storage to be
  559.     in the lowest memory available in the heap. Window storage can differ widely
  560.     amongst applications depending on how many windows are created and disposed. */
  561.  
  562. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  563.     this module. If an error is detected, instead of merely doing an ExitToShell,
  564.     which leaves the user without much to go on, we call AlertUser, which puts
  565.     up a simple alert that just says an error occurred and then calls ExitToShell.
  566.     Since there is no other cleanup needed at this point if an error is detected,
  567.     this form of error- handling is acceptable. If more sophisticated error recovery
  568.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  569.  
  570. #pragma segment Initialize
  571. void Initialize()
  572. {    Handle        menuBar;
  573.     long        total, contig;
  574.     EventRecord event;
  575.     short        count;
  576.  
  577.     gInBackground = false;
  578.  
  579.     InitGraf((Ptr) &qd.thePort);
  580.     InitFonts();
  581.     InitWindows();
  582.     InitMenus();
  583.     TEInit();
  584.     InitDialogs(nil);
  585.     InitCursor();
  586.     
  587.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  588.          if you are using it. */
  589.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  590.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  591.         of checking for port availability themselves. */
  592.     
  593.     /*    This next bit of code is necessary to allow the default button of our
  594.         alert be outlined.
  595.         1.02 - Changed to call EventAvail so that we don't lose some important
  596.         events. */
  597.      
  598.     for (count = 1; count <= 3; count++)
  599.         EventAvail(everyEvent, &event);
  600.     
  601.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  602.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  603.         call to SysEnvirons by calling it after initializing AppleTalk. */
  604.      
  605.     SysEnvirons(kSysEnvironsVersion, &gMac);
  606.     
  607.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  608.     
  609.     if (gMac.machineType < 0) AlertUser();
  610.     
  611.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  612.         in TrapAvailable if a tool trap value is out of range. */
  613.         
  614.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent);
  615.  
  616.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  617.         ApplicationZone, and StackSpace and comparing that to the minimum size we told
  618.         MultiFinder we needed. This did not work well because it assumed too much about
  619.         the relationship between what we asked MultiFinder for and what we would actually
  620.         get back, as well as how to measure it. Instead, we will use an alternate
  621.         method comprised of two steps. */
  622.      
  623.     /*    It is better to first check the size of the application heap against a value
  624.         that you have determined is the smallest heap the application can reasonably
  625.         work in. This number should be derived by examining the size of the heap that
  626.         is actually provided by MultiFinder when the minimum size requested is used.
  627.         The derivation of the minimum size requested from MultiFinder is described
  628.         in Sample.h. The check should be made because the preferred size can end up
  629.         being set smaller than the minimum size by the user. This extra check acts to
  630.         insure that your application is starting from a solid memory foundation. */
  631.      
  632.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  633.     
  634.     /*    Next, make sure that enough memory is free for your application to run. It
  635.         is possible for a situation to arise where the heap may have been of required
  636.         size, but a large scrap was loaded which left too little memory. To check for
  637.         this, call PurgeSpace and compare the result with a value that you have determined
  638.         is the minimum amount of free memory your application needs at initialization.
  639.         This number can be derived several different ways. One way that is fairly
  640.         straightforward is to run the application in the minimum size configuration
  641.         as described previously. Call PurgeSpace at initialization and examine the value
  642.         returned. However, you should make sure that this result is not being modified
  643.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  644.         PurgeSpace. Make sure to remove that call before shipping, though. */
  645.     
  646.     /* ZeroScrap(); */
  647.  
  648.     PurgeSpace(&total, &contig);
  649.     if (total < kMinSpace) AlertUser();
  650.  
  651.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  652.         to check memory is that we can now give the user an alert to tell him/her what
  653.         happened. Although it is possible that the memory situation could be worsened by
  654.         displaying an alert, MultiFinder would gracefully exit the application with
  655.         an informative alert if memory became critical. Here we are acting more
  656.         in a preventative manner to avoid future disaster from low-memory problems. */
  657.  
  658.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  659.     if ( menuBar == nil ) AlertUser();
  660.     SetMenuBar(menuBar);                    /* install menus */
  661.     DisposeHandle(menuBar);
  662.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  663.     DrawMenuBar();
  664.     
  665. } /*Initialize*/
  666.  
  667. /*    Check to see if a window belongs to the application. If the window pointer
  668.     passed was NIL, then it could not be an application window. WindowKinds
  669.     that are negative belong to the system and windowKinds less than userKind
  670.     are reserved by Apple except for windowKinds equal to dialogKind, which
  671.     mean it is a dialog.
  672.     1.02 - In order to reduce the chance of accidentally treating some window
  673.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  674.     is userKind. If you add different kinds of windows to Sample you'll need
  675.     to change how this all works. */
  676.  
  677. #pragma segment Main
  678. Boolean IsAppWindow(window)
  679.     WindowPtr    window;
  680. {
  681.     short        windowKind;
  682.  
  683.     if ( window == nil )
  684.         return false;
  685.     else {    /* application windows have windowKinds = userKind (8) */
  686.         windowKind = ((WindowPeek) window)->windowKind;
  687.         return ( windowKind == userKind );
  688.     }
  689. } /*IsAppWindow*/
  690.  
  691.  
  692. /* Check to see if a window belongs to a desk accessory. */
  693.  
  694. #pragma segment Main
  695. Boolean IsDAWindow(window)
  696.     WindowPtr    window;
  697. {
  698.     if ( window == nil )
  699.         return false;
  700.     else    /* DA windows have negative windowKinds */
  701.         return ( ((WindowPeek) window)->windowKind < 0 );
  702. } /*IsDAWindow*/
  703.  
  704.  
  705. /*    Check to see if a given trap is implemented. This is only used by the
  706.     Initialize routine in this program, so we put it in the Initialize segment.
  707.     The recommended approach to see if a trap is implemented is to see if
  708.     the address of the trap routine is the same as the address of the
  709.     Unimplemented trap. */
  710. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  711.     if a ToolTrap is out of range of a pre-MacII ROM. */
  712.  
  713. #pragma segment Initialize
  714. // check to see if a given trap is implemented. We follow IM VI-3-8.
  715.  
  716. Boolean TrapAvailable(short theTrap)
  717. {
  718.     TrapType theTrapType;
  719.     short numToolboxTraps;
  720.     
  721.     if ((theTrap & 0x0800) > 0)
  722.         theTrapType = ToolTrap;
  723.     else
  724.         theTrapType = OSTrap;
  725.  
  726.     if (theTrapType == ToolTrap)
  727.     {
  728.         theTrap = theTrap & 0x07ff;
  729.         if (NGetTrapAddress(_InitGraf, ToolTrap) == NGetTrapAddress(0xaa6e, ToolTrap))
  730.             numToolboxTraps = 0x0200;
  731.         else
  732.             numToolboxTraps = 0x0400;
  733.         if (theTrap >= numToolboxTraps)
  734.             theTrap = _Unimplemented;
  735.     };
  736.  
  737.     return (NGetTrapAddress(theTrap, theTrapType) != NGetTrapAddress(_Unimplemented, ToolTrap));
  738. }
  739.  
  740.  
  741. /*    Display an alert that tells the user an error occurred, then exit the program.
  742.     This routine is used as an ultimate bail-out for serious errors that prohibit
  743.     the continuation of the application. Errors that do not require the termination
  744.     of the application should be handled in a different manner. Error checking and
  745.     reporting has a place even in the simplest application. The error number is used
  746.     to index an 'STR#' resource so that a relevant message can be displayed. */
  747.  
  748. #pragma segment Main
  749. void AlertUser()
  750. {
  751.     short        itemHit;
  752.  
  753.     SetCursor(&qd.arrow);
  754.     itemHit = Alert(rUserAlert, nil);
  755.     ExitToShell();
  756. } /* AlertUser */